import { TaskFieldNameMappingEnum } from '@model/enum/FieldMappingEnum.ts'
import { isSelect, isMultiSelect, expandField } from '@src/component/form/util'
import Filter from '@src/filter/filter';
import { getTimestamp } from 'pub-bbx-utils';
/** 将form对象转成客户对象，用于提交表单 */
export function packToTask(fields, form){
  let task = {
    id: form.id,
    attribute: {},
    tick: form.tick || 0,
  };

  let subForms = []
  expandField(fields).forEach(field => {
    let {fieldName, isSystem} = field;
    let value = form[fieldName];

    if(fieldName === TaskFieldNameMappingEnum.Customer){
      let customer = form.customer || [];
      // customer
      if(customer[0]){
        task.customer = {
          id: customer[0].value
        };
      }

      // 客户联系人
      task.linkman = {};
      if(form.linkman && form.linkman[0]){
        let linkman = form.linkman[0];
        let { value, name, phone } = linkman;

        task.linkman = { id: value, name, phone };
      }
      
      // 客户地址
      task.address = {};
      if(form.address && form.address[0]){
        let address = form.address[0];
        let taddress = {};

        taddress.id = address.value;
        taddress.country = address.country || '';
        taddress.province = address.province;
        taddress.city = address.city;
        taddress.dist = address.dist;
        taddress.latitude = address.latitude;
        taddress.longitude = address.longitude;
        taddress.address = address.address;

        task.address = address;
      } 

      // 产品
      task.products = [];
      // 获取质保字段
      let formQuality = {}
      if(form.quality) {
        let { qualityEndTime = '', qualityStartTime = '', qualityStatus = '' } = form.quality
        formQuality = {
          qualityEndTime,
          qualityStartTime,
          qualityStatus
        }
      }

      if(form.product && form.product.length > 1) {
        // 非质保工单
        form.product.map(product => {
          task.products.push({
            catalogId: product.catalogId,
            id: product.id,
            name: product.name,
            serialNumber: product.serialNumber,
            type: product.type,
            customerId:product.customerId,
            qualityStatus: product.qualityStatus || '',
            qualityStartTime: product.qualityStartTime || '',
            qualityEndTime: product.qualityEndTime || ''
          })
        })
      } else if(form.product && form.product.length === 1){
        // 质保工单
        form.product.map(product => {
          task.products.push({
            catalogId: product.catalogId,
            id: product.id,
            name: product.name,
            serialNumber: product.serialNumber,
            type: product.type,
            customerId:product.customerId,
            ...formQuality
          })
        })
      }
      
      return;
    }

    // 服务商
    if(fieldName === TaskFieldNameMappingEnum.ServiceProviders) {
      task.serviceProviders = []
      if(form.serviceProviders && form.serviceProviders.length > 0) {
        form.serviceProviders.forEach((provider, index) => {
          if(provider.attribute) {
            task.serviceProviders.push(provider)
          } else {
            task.serviceProviders.push({
              serviceProviderId: provider.serviceProviderId
            })
            delete provider.serviceProviderId
            task.serviceProviders[index]['attribute'] = provider
          }
        })
      }
      return
    }

    // 关联表单
    if(field.formType === 'relationForm') {
      if(Array.isArray(value) && value.length > 0 ){
        value.forEach(item =>{
          let attribute = {
            parentFieldName:field.fieldName,
            ...item
          }
          subForms.push({ attribute })
        })
      }
      task.subForms = subForms
      return
    }
    

    if (field.formType === TaskFieldNameMappingEnum.Address && !field.isSystem && value) {
      let all = Filter.prettyAddress(value);

      if(all) {
        value.all = all;
      }
    }
    
    if ((field.formType === TaskFieldNameMappingEnum.Location) && !value.isHaveLocation) {
      value = {};
    }

    if (field.formType === TaskFieldNameMappingEnum.PlanTime && value) {
      value = getTimestamp(value)
    }
    if (field.formType === TaskFieldNameMappingEnum.PlanStartTime && value) {
      value = getTimestamp(value)
    }
    if (field.formType === TaskFieldNameMappingEnum.PlanEndTime && value) {
      value = getTimestamp(value)
    }

    if (fieldName === TaskFieldNameMappingEnum.Attachment && value) {
      // 拼附件和回执附件
      value = value.concat(form.receiptAttachment).filter(attachment => !!attachment);
    }

    isSystem == 0
      ? task.attribute[fieldName] = value
      : task[fieldName] = value;
  });

  return task;
}

/** 
 * @description 将工单对象转成form表单，用于初始化表单 
*/
export function packToForm(fields, data){
  // TODO: 临时注掉，如果有需要再修改
  // if (!data.id) return;
  
  // fix:22626，attribute解构数据放到最上面，避免attribute里面有id时把真实的工单id给覆盖了
  let task = {
    ...data.attribute,
    id: data.id,
    taskNo: data.taskNo,
    templateName: data.templateName,
    templateId: data.templateId,
  };
  
  let fieldValue = null
  
  expandField(fields).forEach(field => {
    if(!field.setting) {
      field.setting = {}
    } 
    let { fieldName, isSystem } = field;
    let value = data[fieldName];
    
    if(fieldName === TaskFieldNameMappingEnum.Customer){
      // 初始化客户
      task.customer = [];
      if(value?.id) {
        task.customer = [{
          value: value?.id,
          label: value?.name,
          customerManager: value?.customerManager,
          synergies: value?.synergies
        }];
      }
      
      // 初始化联系人
      task.linkman = [];
      if(data.tlmId) {
        task.linkman = [{
          value: data?.tlmId,
          label: data?.tlmName + data?.tlmPhone,
          name: data?.tlmName,
          phone: data?.tlmPhone
        }];
      }

      // 初始化地址
      task.address = [];
      if (data?.taddress?.id) {
        task.address = [{
          value: data.taddress.id,
          label: Filter.prettyAddress(data.taddress,'-'),
          ...data.taddress
        }];
      }

      // 初始化产品
      task.product = (data.products || []).filter(item => item && item.id).map(item => {
        item.value = item.id;
        item.label = item.name;
        return item
      });

      return;
    }
    
    if (field.formType === TaskFieldNameMappingEnum.PlanTime && value) {
      let { dateType = 'date' } = field.setting;
      value = dateType == 'date' ? value.substr(0, 10) : value;
    }
    
    if (fieldName === TaskFieldNameMappingEnum.Attachment && value) {
      // 分离附件和回执附件
      if (value.length) {
        task.receiptAttachment = value.filter(img => img.receipt);
        value = value.filter(img => !img.receipt);
      }
    }
    
    // 产品关联查询
    if (field.formType === TaskFieldNameMappingEnum.RelationProduct) {
      let fieldValue = task[fieldName];
      if (!Array.isArray(fieldValue) && fieldValue) task[fieldName] = [fieldValue];
    }
    
    // 字段值
    fieldValue = field.isSystem === 1 ? data[fieldName] : data?.attribute?.[fieldName]
    
    // 多选改单选,若原来有值则保留第一个
    if(isSelect(field) && Array.isArray(fieldValue)) {
      fieldValue = (fieldValue && fieldValue.length >= 1) ? fieldValue[0] : ''
    }
    // 单选改多选，将原值加入数组
    if(isMultiSelect(field) && !Array.isArray(fieldValue)) {
      fieldValue = fieldValue ? [fieldValue] : []
    }

    if(field.formType === 'relationForm'){
      let list = data.subForms || []
      fieldValue = []
      list.forEach(item => {
        if(item?.attribute?.parentFieldName && fieldName === item.attribute.parentFieldName){
          let obj = { ...item.attribute }
          fieldValue.push(obj)
        }
      })
    }
    
    if (isSystem == 1) {
      task[fieldName] = value
    } else {
      task[fieldName] = fieldValue
    }
    
  })
  
  return task;
}
